<template>
  <div class="webchatDataBox">
    <tabs :tabPane="tabPaneList" @tab-click="handleClick" v-model="activeName">
    </tabs>
    <continer class="webchatContainer" :isNoTabs="false">
      <template slot="search">
        <quickSearch
          :advForm="quickSearchForm"
          @QuickSearch="getWebchatListSearch"
        ></quickSearch>
      </template>
      <template slot="oprate">
        <customSearch
          v-if="activeName === 'session'"
          ref="customSearch"
          class="customSearch"
          :fieldList="fieldList"
          :fieldSelectList="fieldSelectList"
          :customList="customList"
          :conditionList="conditionList"
          @deleteCustomClick="deleteCustomClick"
          @popverShow="popverShow"
          @saveCondition="saveConditionFun"
          @handleSearch="handleSearch"
        ></customSearch>
        <el-button type="primary" size="mini" @click="pageChange(1)"
          >刷新</el-button
        >
      </template>
      <template slot="content">
        <webchatTable
          v-loading="showLoading"
          v-if="isShowTabel"
          :headers="tableHeaders"
          :data="webchatList"
          :pagingData="pageData"
          :headersConfig="true"
          :selection="true"
          :batchs="configBatchs"
          ref="webchatTableRef"
          @batchClick="batchClick"
          @pageChange="pageChange"
          @pageSizeChange="pageSizeChange"
          @checkHeadersChange="checkHeadersChange"
        >
          <template slot="column">
            <template v-for="(item, index) in checkHeaders">
              <u-table-column
                v-if="
                  ![
                    'oprate',
                    'status',
                    'accessName',
                    'sessionTags',
                    'qualityStatus'
                  ].includes(item.prop) && item.show
                "
                :resizable="false"
                :prop="item.prop"
                :label="item.label"
                :key="item.label + index"
                :sortable="item.sortable"
                :min-width="item.width > 0 ? item.width : ''"
                :show-overflow-tooltip="item.width > 0"
                align="left"
              >
              </u-table-column>
              <u-table-column
                v-if="item.prop === 'qualityStatus' && item.show"
                :resizable="false"
                :prop="item.prop"
                :label="item.label"
                :key="item.label + index"
                :min-width="item.width > 0 ? item.width : ''"
                :show-overflow-tooltip="item.width > 0"
                align="left"
              >
                <template slot-scope="scope">
                  {{ scope.row | filterQualityStatus }}
                </template>
              </u-table-column>
              <u-table-column
                v-if="item.prop === 'accessName' && item.show"
                :resizable="false"
                :prop="item.prop"
                :label="item.label"
                :key="item.label + index"
                :min-width="item.width > 0 ? item.width : ''"
                :show-overflow-tooltip="item.width > 0"
                align="left"
              >
                <template slot-scope="scope">
                  <i
                    class="V7_iconfont"
                    :class="scope.row.platform | handlePlatformIcon"
                  ></i>
                  {{ scope.row.accessName }}
                </template>
              </u-table-column>
              <u-table-column
                v-if="item.prop === 'status' && item.show"
                :resizable="false"
                :prop="item.prop"
                :label="item.label"
                :key="item.label + index"
                :min-width="item.width > 0 ? item.width : ''"
                :show-overflow-tooltip="item.width > 0"
                align="left"
              >
                <template slot-scope="scope">
                  <i
                    class="V7_iconfont V7_iconV7tubiao_dian"
                    :style="scope.row.status._id | handleStatusIcon"
                  ></i>
                  {{ scope.row.status.name }}
                </template>
              </u-table-column>
              <u-table-column
                v-if="item.prop === 'sessionTags' && item.show"
                :resizable="false"
                :prop="item.prop"
                :label="item.label"
                :key="index"
                :min-width="item.width > 0 ? item.width : ''"
                :show-overflow-tooltip="item.width > 0"
                align="left"
              >
                <template slot-scope="scope">
                  <span
                    class="tagsItem"
                    v-if="scope.row.sessionTags.length > 0"
                    :style="{
                      border: item.color ? 'none' : '1px solid #ecf0f3',
                      background: scope.row.sessionTags[0].color
                        ? scope.row.sessionTags[0].color
                        : '#fff',
                      color: scope.row.sessionTags[0].color ? '#fff' : '#686e84'
                    }"
                  >
                    {{ scope.row.sessionTags[0].name }}</span
                  >
                  <span v-else>--</span>
                  <span
                    v-if="scope.row.sessionTags.length > 1"
                    class="tagsItem"
                    :style="{
                      border: item.color ? 'none' : '1px solid #ecf0f3',
                      background: scope.row.sessionTags[0].color
                        ? scope.row.sessionTags[0].color
                        : '#fff',
                      color: scope.row.sessionTags[0].color ? '#fff' : '#686e84'
                    }"
                    >+{{ scope.row.sessionTags.length - 1 }}</span
                  >
                </template>
              </u-table-column>
              <u-table-column
                :label="item.label"
                v-if="item.prop === 'oprate' && item.show"
                :key="item.label + index"
                align="left"
                fixed="right"
                width="70"
              >
                <template slot-scope="scope">
                  <span class="oprate-btn" @click="handleDetail(scope.row)"
                    >详情</span
                  >
                  <el-tooltip effect="dark" content="主动会话" placement="top">
                    <span
                      v-if="
                        activeName === 'session' &&
                        scope.row.status._id === 'finish' &&
                        userInfo.functions.indexOf(
                          'webchat_session_chat_active'
                        ) > -1 &&
                        scope.row.finishKey !== 'black_finish'
                      "
                      @click="initiativeClick(scope.row)"
                      class="
                        oprate_span
                        V7_iconfont V7_iconV7tubiao_zhudonghuihua
                      "
                    ></span>
                  </el-tooltip>
                  <el-tooltip
                    effect="dark"
                    :content="getQtText(scope.row)"
                    placement="top"
                  >
                    <span
                      v-functions="['webchat_session_chat_commit_cancel_qc']"
                      @click="handleQualitytesting(scope.row, scope.$index)"
                      :class="[
                        'oprate_span',
                        'V7_iconfont',
                        getQtIcon(scope.row)
                      ]"
                    ></span>
                  </el-tooltip>
                </template>
              </u-table-column>
            </template>
          </template>
        </webchatTable>
        <resizeDrawer
          title="详情"
          :drawer="isShowDrawer"
          direction="rtl"
          :modal-append-to-body="false"
          :isShowMoreBtn="false"
          @closeDraw="closeDraw"
          ref="drawer"
          :size="700"
          class="webchat-detail-drawer"
        >
          <template slot="column">
            <div
              style="position: absolute; width: calc(100% - 48px); height: 100%"
            >
              <webchatDataSummary
                :type="activeName"
                :isShowDrawer="isShowDrawer"
              ></webchatDataSummary>
            </div>
          </template>
        </resizeDrawer>
        <exportDialog
          ref="exportDialogRef"
          @dialog-save="dialogSave"
        ></exportDialog>
      </template>
    </continer>
    <webchatVideo
      v-if="videoInfo.isShowVideo"
      :replayUrl="videoInfo.videoUrl"
      :chatMsg="videoInfo.chatMsg"
      @closeVideoReplay="closeVideoReplay"
    >
    </webchatVideo>
  </div>
</template>
<script lang='ts'>
import { Component, Vue, Ref } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import quickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import customSearch from '@/views/dataCenter/callData/customSearch.vue'
import webchatTable from '@/components/configCommon/table.vue'
import exportDialog from '@/components/exportDialog/index.vue'
import webchatDataSummary from '@/views/dataCenter/webchatData/webchatDataSummary.vue'
import tabs from '@/components/configCommon/configTabs.vue'
import webchatVideo from '@/views/webchat/common/webchatVideo.vue'
import { deepClone, millsToDate, getFormatDateTime, isHasFuncOrMenus } from '@/utils/common'
import { WebchatModule } from '@/store/modules/webchat'
import resizeDrawer from '@/components/globalTool/resizeDrawer/drawer.vue';
@Component({
  name: 'webchatData',
  components: {
    continer,
    quickSearch,
    customSearch,
    webchatTable,
    webchatDataSummary,
    tabs,
    webchatVideo,
    exportDialog,
    resizeDrawer
  },
  filters: {
    handlePlatformIcon (type: string) { // 处理会话来源图标
      switch (type) {
        case 'pc': // pc
          return 'V7_iconV7tubiao_qudao-wangzhan'
        case 'wap': // wap、h5
          return 'V7_iconV7tubiao_qudao-H5'
        case 'weixin': // 微信
          return 'V7_iconV7tubiao_weixingongzhonghao'
        case 'wxmini': // 微信小程序
          return 'V7_iconV7tubiao_weixinxiaochengxu'
        case 'sdk': // sdk
          return 'V7_iconV7tubiao_app'
        case 'wxsdk': // 微信小程序sdk
          return 'V7_iconV7tubiao_weixinxiaochengxu1'
        case 'wxwork': // 企业微信
          return 'V7_iconV7tubiao_qiyeweixin'
        case 'ocpc': // 百度bcp
          return 'V7_iconV7tubiao_baiduBCP'
        case 'wxkf': // 微信客服
          return 'V7_iconV7tubiao_weixinkefu'
      }
    },
    handleStatusIcon (status: string) { // 处理会话状态icon
      if (['undeal', 'queue'].includes(status)) { // 排队中
        return 'color: #FAAE14'
      } else if (['robot', 'deal'].includes(status)) { // 处理中, 机器人处理中
        return 'color: #2ED47A'
      } else if (status === 'finish') { // 已结束
        return 'color: #FC6B5C'
      }
    },
    filterQualityStatus (row: any) {
      let qtStatus: string
      if (row.qualityTime) {
        qtStatus = '已评分'
      } else {
        if (row.applyQualityTime) {
          qtStatus = '已提交未评分'
        } else {
          qtStatus = '未提交'
        }
      }
      return qtStatus
    }
  }
})
export default class WebchatData extends Vue {
  [x: string]: any
  @Ref() private webchatTableRef!: webchatTable
  @Ref() private exportDialogRef !: exportDialog
  private $getCache: any
  private $store: any
  private $bus: any
  private $message: any
  private $router: any

  private tabPaneList = [
    {
      label: '会话记录',
      name: 'session',
      _id: 'webchat_session_chat'
    },
    {
      label: '留言记录',
      name: 'leave',
      _id: 'webchat_session_leave'
    }
  ]

  private videoInfo = { // 视频窗口参数
    isShowVideo: false, // 是否展示视频播放窗口
    videoUrl: '', // 地址
    chatMsg: {} // 会话信息
  }

  private userInfo = {}

  private activeName = 'session' // tab默认值

  private platformObj = {} // 会话来源对象

  private isShowTabel = false // 是否展示

  private showLoading = false // loading

  private isShowDrawer = false // 是否展示会话详情抽屉

  private query: any = {}

  private advanceQuery: any = {} // 高级搜索

  private checkHeaders = [] // 表头

  private agentList = [] // 座席列表

  private leaveSessionType = { // 留言会话结束类型
    undeal: { name: '未领取', _id: 'undeal' },
    deal: { name: '已领取', _id: 'deal' },
    finish: { name: '已处理', _id: 'finish' }
  }

  private tableCheckedList: any = []

  private quickSearchForm: any = { // 快捷检索数据（时间条件，类型）
    form: {
      visitorName: '', // 访客名
      userId: [], // 用户id
      createTime: [ // 创建时间 默认显示最近七天
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 6), '').split(' ')[0] + ' 00:00:00',
        getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59'
      ]
    },
    advSearchOptions: []
  }

  private tableHeaders = [
    { label: '客户昵称', prop: 'visitorName', width: 110, show: true },
    { label: '会话记录ID', prop: '_id', width: 120, show: false },
    { label: '渠道接入号', prop: 'accessName', width: 120, show: true },
    { label: '技能组', prop: 'queueName', width: 120, show: true },
    { label: '座席名称', prop: 'agentName', width: 120, show: true },
    { label: '会话状态', prop: 'status', width: 120, show: true },
    { label: '创建时间', prop: 'createTime', width: 150, show: true },
    { label: '转人工时间', prop: 'convertManualTime', width: 150, show: false },
    { label: '转人工成功时间', prop: 'manualTime', width: 150, show: false },
    { label: '结束时间', prop: 'endTime', width: 150, show: false },
    { label: '首响时间', prop: 'agentFirstReplyTime', width: 150, show: false },
    { label: '首响时长', prop: 'agentFirstReplyLength', width: 150, show: true },
    // { label: '会话时长', prop: 'sesssionTimeLength', width: 120, show: true },
    { label: '总消息数', prop: 'totalMessageCount', width: 80, show: true },
    { label: '访客消息数', prop: 'visitorMessageCount', width: 80, show: false },
    { label: '座席消息数', prop: 'agentReplyMessageCount', width: 80, show: false },
    { label: '访问来源', prop: 'seoSource', width: 120, show: false },
    { label: '访问来源关键字', prop: 'seoKeywords', width: 150, show: false },
    { label: '会话结束类型', prop: 'finishReason', width: 120, show: false },
    { label: '地域', prop: 'area', sortable: true, width: 120, show: false },
    { label: 'IP地址', prop: 'ip', width: 120, show: false },
    { label: '质检状态', prop: 'qualityStatus', width: 120, show: false },
    { label: '质检分数', prop: 'gradeScore', width: 120, show: false },
    { label: '接入别名', prop: 'userAlias', width: 120, show: false },
    { label: '操作', prop: 'oprate', disenable: true }
  ]

  private tableData = [] // table数据

  private pageData = { total: 0, limit: 10, page: 1 }
  private configBatchs: any[] = []

  private chatBatchs = [
    { name: '批量导出记录', action: 'handleBatchExport', _id: 'webchat_session_chat_batch_export' },
    { name: '批量导出内容', action: 'handleBatchContentExport', _id: 'webchat_content_session_chat_batch_export' },
    { name: '批量提交质检', action: 'handleBatchSubmitSq', _id: 'webchat_session_chat_batch_commit_cancel_qc' },
    { name: '批量撤销质检', action: 'handleBatchCancelSq', _id: 'webchat_session_chat_batch_commit_cancel_qc' }
  ]

  private leaveBatchs = [
    { name: '批量导出记录', action: 'handleBatchExport', _id: 'webchat_session_leave_batch_export' }
  ]

  private deaultCustomList = [ // 高级搜索默认列表
    { name: '全部在线会话记录', default: true, advanceQuery: [[]] },
    {
      name: '我的在线会话记录',
      default: true,
      advanceQuery: [[{ fieldKey: 'userId', fieldOperator: 'eq', fieldValue: [(this as any).$store.state.common.session.user._id] }]]
    }
  ]

  private dialogTitle = ''

  private customList: any = []

  private conditionList = { // 自定义筛选项条件
    // 'eq'（等于）, 'neq'（不等于）, 'in'（包含）, 'nin'（不包含）, 'empty'（为空）, 'nempty'（不为空）
    // 'gt'（大于）, 'gte'（大于等于）, 'lt'（小于）, 'lte'（小于等于）, 'between'（介于）, 'nbtn'（不介于）
    'visitorName': { type: 'string', condition: ['in'] }, // 访客名
    '_id': { type: 'string', condition: ['in', 'nin'] }, // 会话id
    'platform': { type: 'select', condition: ['eq', 'neq', 'in', 'nin'] },
    'accessId': { type: 'select', condition: ['eq', 'neq', 'in', 'nin'], props: { label: 'name', value: 'accessId' } }, // 接入号
    'toPeer': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 技能组
    // usergentName: { type: 'string', condition: ['empty', 'nempty', 'eq', 'in', 'nin'] }, // 座席昵称
    'userId': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'], props: { label: 'agentName', value: '_id' } }, // 座席名称/昵称
    'status': { type: 'select', condition: ['eq', 'neq', 'in', 'nin'] }, // 状态
    'createTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] }, // 会话创建时间
    'convertManualTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] }, // 转人工时间
    'manualTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] }, // 转人工成功时间
    'endTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] }, // 会话结束时间
    'agentFirstReplyTime': { type: 'date', condition: ['gt', 'lt', 'between'] }, // 座席回复时间
    'totalMessageCount': { type: 'number', condition: ['eq', 'gte', 'lte'], returntype: 'number' }, // 总消息数
    'visitorMessageCount': { type: 'number', condition: ['eq', 'gte', 'lte'], returntype: 'number' }, // 访客消息数
    'agentReplyMessageCount': { type: 'number', condition: ['eq', 'gte', 'lte'], returntype: 'number' }, // 座席消息数
    'seoSource': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in'] }, // 访问来源
    'seoKeywords': { type: 'string', condition: ['empty', 'nempty', 'eq', 'neq', 'in'] }, // 搜索关键字
    'finishKey': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 结束类型
    'area': { type: 'string', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 地域
    'ip': { type: 'string', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // ip
    'sessionType': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 会话类型
    'satisfactionData.satisfactionName': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 满意度名称
    'sessionTags': { // 会话标签
      type: 'cascader',
      condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'],
      props: { label: 'name', value: '_id', children: 'children', multiple: true, emitPath: 'false' }
    },
    'messageKeywords': { // 会话内容搜索
      type: 'select',
      condition: ['in'],
      props: { multiple: true, allowCreate: true, allowCreateLength: 3 }
    },
    'qualityStatus': {
      type: 'select',
      condition: ['eq', 'neq', 'in', 'nin']
    },
    'gradeScore': {
      type: 'number',
      condition: ['eq', 'gte', 'lte', 'nin', 'between']
    },
    'userAlias': {
      type: 'string',
      condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty']
    }
  }

  private fieldList = [ // 自定义筛选项
    { label: '客户昵称', prop: 'visitorName' },
    { label: '会话ID', prop: '_id' },
    { label: '渠道来源', prop: 'platform' },
    { label: '渠道接入号', prop: 'accessId' },
    { label: '技能组', prop: 'toPeer' },
    { label: '座席名称/工号', prop: 'userId' },
    // { label: '座席昵称', prop: 'userId' },
    { label: '会话状态', prop: 'status' },
    { label: '创建时间', prop: 'createTime' },
    { label: '转人工时间', prop: 'convertManualTime' },
    { label: '转人工成功时间', prop: 'manualTime' },
    { label: '结束时间', prop: 'endTime' },
    { label: '首响时间', prop: 'agentFirstReplyTime' },
    { label: '总消息条数', prop: 'totalMessageCount' },
    { label: '访客消息条数', prop: 'visitorMessageCount' },
    { label: '座席消息条数', prop: 'agentReplyMessageCount' },
    { label: '访问来源', prop: 'seoSource' },
    { label: '访问来源关键字', prop: 'seoKeywords' },
    { label: '会话结束类型', prop: 'finishKey' },
    { label: '地域', prop: 'area' },
    { label: 'IP地址', prop: 'ip' },
    { label: '会话类型', prop: 'sessionType' },
    { label: '满意度名称', prop: 'satisfactionData.satisfactionName' },
    { label: '会话标签', prop: 'sessionTags' },
    { label: '会话内容', prop: 'messageKeywords' },
    { label: '质检状态', prop: 'qualityStatus' },
    { label: '质检分数', prop: 'gradeScore' },
    { label: '接入别名', prop: 'userAlias', width: 120, show: false }
  ]

  private fieldSelectList = { // 自定义选筛选下拉内容
    'status': [],
    'accessId': [],
    'finishKey': [],
    'seoSource': [],
    'platform': [],
    'toPeer': [],
    'userId': [],
    'sessionType': [],
    'satisfactionData.satisfactionName': [],
    'sessionTags': [],
    'qualityStatus': [
      { name: '未提交', _id: 'notApply' },
      { name: '已提交未评分', _id: 'apply' },
      { name: '已评分', _id: 'quality' }
    ]
  }

  get webchatList () {
    const submenu = this.activeName === 'session' ? 'dataCenterSession' : 'dataCenterLeave'
    return this.$store.state.webchat.webchatList[submenu] || []
  }

  get webchatLabelTreeObj () {
    if (this.$store.state.common.publicCache.sessionTagsTreeObj) {
      return this.$store.state.common.publicCache.sessionTagsTreeObj
    } else {
      return []
    }
  }

  private deleteCustomClick (obj: any) { // 删除高级搜索
    const data = { url: '/im-center/action/webchat/quickQuery/delete ', method: 'POST', data: { _id: obj._id } }
    WebchatModule.webchatCommonAction(data).then((res: any) => {
      if (res.success) {
        this.getConditionList()
      }
    })
  }

  private handleClick (type: any) { // tab切换
    this.activeName = type.name
    this.configBatchs = this.activeName === 'session' ? this.chatBatchs : this.leaveBatchs
    this.pageData.page = 1
    this.getWebchatTabelHeaders()
    this.getWebchatList()
  }

  private popverShow () { // 高级搜索弹窗
    this.getConditionList()
  }

  private saveConditionFun (obj: any) { // 保存高级搜索条件
    const queryObj: any = { name: obj.name, advanceQuery: obj.advanceQuery }
    if (obj.currentCustomId) {
      queryObj._id = obj.currentCustomId
    }
    const data = { url: '/im-center/action/webchat/quickQuery/save', method: 'POST', data: queryObj }
    WebchatModule.webchatCommonAction(data).then((res: any) => {
      if (res.success) {
        this.getConditionList()
      }
    })
  }

  private getConditionList (): void { // 获取高级搜索条件列表
    const data = { url: '/im-center/action/webchat/quickQuery/list', method: 'GET' }
    WebchatModule.webchatCommonAction(data).then((res: any) => {
      if (res.success) {
        this.customList = this.deaultCustomList.concat(res.data.list)
      }
    })
  }

  private initiativeClick (row: any) { // 主动会话
    const url = '/im-center/action/webchat/initiatingSession'
    const sendData = { sessionId: row._id, visitorId: row.visitorId }
    const actionData = { url, method: 'POST', data: sendData }
    WebchatModule.webchatCommonAction(actionData).then((res: any) => {
      if (res) {
        this.$message.success('主动会话成功')
      }
    })
  }

  private getWebchatList (searchType?: string) { // 查会话表格
    this.showLoading = true
    if (searchType === 'advanceQuery') {
      this.query = {}
      if (this.advanceQuery && this.advanceQuery.length > 0) {
        this.query.advanceQuery = this.advanceQuery
        for (let i = 0; i < this.advanceQuery.length; i++) {
          if (this.advanceQuery[i][0] && this.advanceQuery[i][0].fieldKey === 'messageKeywords') {
            WebchatModule.SET_MESSAGEKEYWORKS(this.advanceQuery[i][0].fieldValue[0])
            break
          } else {
            WebchatModule.SET_MESSAGEKEYWORKS([])
          }
        }
      } else {
        delete this.query.advanceQuery
      }
    } else {
      Object.keys(this.quickSearchForm.form).forEach((key) => {
        console.log(key)
        if (this.quickSearchForm.form[key] && this.quickSearchForm.form[key].length > 0) {
          this.query[key] = this.quickSearchForm.form[key]
        }
      })
    }
    let url = '/im-center/action/webchat/queryWebchatSession'
    let sendData = Object.assign({ limit: this.pageData.limit, page: this.pageData.page, submenu: 'webchat_all' }, this.query)
    if (this.activeName === 'leave') {
      url = '/im-center/action/webchat/queryLeaveSession'
      sendData = Object.assign({ limit: this.pageData.limit, page: this.pageData.page, submenu: 'all' }, this.query)
    }
    const actionData = { url, method: 'POST', data: sendData }
    WebchatModule.webchatCommonAction(actionData).then(res => {
      if (res && res.list) {
        const channelList = this.$store.state.common.publicCache.channelList || []
        res.list.forEach((item: any) => {
          const accessObj = channelList.find((channelItem: any) => { // 接入号
            return channelItem.accessId === item.accessId
          })
          item.accessName = accessObj ? accessObj.name : '--'
          const agentObj = this.$store.state.common.publicCache.userListObj[item.userId] // 座席
          item.agentName = agentObj ? agentObj.name : '--'
          const queueObj = this.$store.state.common.publicCache.queueListObj[item.toPeer] // 技能组
          item.queueName = queueObj ? queueObj.name : '--'
          const sessionTypeObj = this.$store.state.common.publicCache.sessionTypeObj[item.sessionType] // 会话类型
          item.sessionType = sessionTypeObj ? sessionTypeObj.name : '--'
          const statusObj = this.activeName === 'session' ? this.$store.state.common.publicCache.statusObj[item.status] : this.leaveSessionType[item.status]// 会话状态
          item.status = statusObj || '--'
          item.satisfactionName = item.satisfactionData && item.satisfactionData.satisfactionName ? item.satisfactionData.satisfactionName : '' // 满意度名称
          if (item.satisfactionData && item.satisfactionData.satisfactionReason.length > 0) { // 满意度标签
            item.satisfactionReason = ''
            item.satisfactionData.satisfactionReason.forEach(reasonItem => {
              item.satisfactionReason += reasonItem + '/'
            })
            item.satisfactionReason = item.satisfactionReason.substring(0, item.satisfactionReason.length - 1)
          } else {
            item.satisfactionReason = '--'
          }
          const sessionTagsInfoObj = {}
          if (item.sessionTagsInfo) {
            item.sessionTagsInfo.forEach(tagInfoItem => {
              sessionTagsInfoObj[tagInfoItem._id] = tagInfoItem
            })
          }
          if (item.sessionTags && item.sessionTags.length > 0) {
            const arr: any = []
            item.sessionTags.forEach((sessionTagItem: any) => {
              if (this.webchatLabelTreeObj[sessionTagItem]) {
                arr.push(this.webchatLabelTreeObj[sessionTagItem])
              } else {
                arr.push(sessionTagsInfoObj[sessionTagItem])
              }
            })
            item.sessionTags = arr
          } else {
            item.sessionTags = []
          }
          item.satisfactionProposal = item.satisfactionData && item.satisfactionData.satisfactionProposal ? item.satisfactionData.satisfactionProposal : '' // 满意度备注
          if (item.manualTimestamp && item.agentFirstReplyTimestamp) {
            item.agentFirstReplyLength = millsToDate(item.agentFirstReplyTimestamp - (item.manualTimestamp || item.createTimestamp)) // 首次响应时长
          } else {
            item.agentFirstReplyLength = '--'
          }
          item = this.handleTableData(item)
        })
        const submenu = this.activeName === 'session' ? 'dataCenterSession' : 'dataCenterLeave'
        WebchatModule.SET_WEBCHAT_LIST({ list: res.list, submenu })
        // this.tableData = res.list
      }
      this.showLoading = false
      this.pageData.total = res.count
    })
  }

  private handleTableData (obj: any) {
    const number: any = ['agentReplyMessageCount', 'visitorMessageCount', 'totalMessageCount', 'gradeScore'] // 需要展示为数组0
    this.tableHeaders.forEach(item => {
      if (number.indexOf(item.prop) > -1) {
        if (!obj[item.prop]) {
          obj[item.prop] = 0
        }
      } else {
        if (!obj[item.prop]) {
          obj[item.prop] = '--'
        }
      }
    })
    return obj
  }

  private dialogSave (data: any) { // 导出弹窗外抛的保存事件
    this.exportDialogRef.setDialogData({ exportDialog: false })
    if (this.dialogTitle === '批量导出会话内容') {
      this.handleBatchContentExport(data.comment)
    } else {
      this.handleBatchExport(data.comment)
    }
  }

  private handleBatchExport (comment: string) {
    const selectList = this.tableCheckedList
    let sendData = {}
    let count = 0
    if (typeof selectList === 'object') { // 单个操作，传ids
      sendData = { ids: selectList || [] }
      count = selectList.length || 0
    } else { // 全选传查询条件
      sendData = { condition: this.query }
      count = this.pageData.total || 0
    }
    const type = this.activeName === 'session' ? 'chatSession' : 'leaveSession'
    const actionData = Object.assign({ limit: this.pageData.limit, page: this.pageData.page, count, comment: comment || '', type }, sendData)
    WebchatModule.webchatCommonAction({ url: '/im-center/action/export/exportWebchat', method: 'POST', data: actionData }).then(res => {
      if (res && res.success && res.data) {
        this.webchatTableRef.cancelSelectFun() // 关闭批量操作栏
        const h = this.$createElement
        this.$message({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, `导出任务${res.data.taskId || ''}进入排队，请前往`),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
      }
    })
  }

  private handleBatchContentExport (comment: string) {
    const selectList = this.tableCheckedList
    let sendData = {}
    let count = 0
    if (typeof selectList === 'object') { // 单个操作，传ids
      sendData = { ids: selectList || [] }
      count = selectList.length || 0
    } else { // 全选传查询条件
      sendData = { condition: this.query }
      count = this.pageData.total || 0
    }
    const type = 'chatSessionContent'
    const actionData = Object.assign({ limit: this.pageData.limit, page: this.pageData.page, count, comment: comment || '', type }, sendData)
    WebchatModule.webchatCommonAction({ url: '/im-center/action/export/exportWebchat', method: 'POST', data: actionData }).then(res => {
      if (res && res.success && res.data) {
        this.webchatTableRef.cancelSelectFun() // 关闭批量操作栏
        const h = this.$createElement
        this.$message({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, `导出任务${res.data.taskId || ''}进入排队，请前往`),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
      }
    })
  }

  private jumpToTransmissionCenter () { // 跳转到传输中心
    if (this.dialogTitle === '批量导出会话内容') {
      this.$router.push('/transmission_center/index/tx_export_task?taskModule=chatSessionContent')
    } else {
      this.activeName === 'session' ? this.$router.push('/transmission_center/index/tx_export_task?taskModule=chatSession') : this.$router.push('/transmission_center/index/tx_export_task?taskModule=leaveSession')
    }
  }

  private getWebchatListSearch (obj) { // 高级搜索事件
    this.webchatTableRef.clearSelection()
    this.pageData.page = 1
    const searchForm = obj.form
    this.query = {}
    if (searchForm) {
      Object.keys(searchForm).forEach((key) => {
        if (searchForm[key] && searchForm[key].length > 0) {
          this.query[key] = searchForm[key]
        }
      })
    }
    this.getWebchatList()
  }

  private pageChange (page: number) { // 翻页
    this.pageData.page = page
    this.getWebchatList()
  }

  private pageSizeChange (size: number) {
    this.pageData.page = 1
    this.pageData.limit = size
    this.getWebchatList()
  }

  private checkHeadersChange (checkList: any, isInit: any) { // 自定义表头
    this.$set(this, 'checkHeaders', checkList)
    if (!isInit) {
      this.saveWebchatTabelHeaders(checkList)
    }
  }

  private batchClick (action: any, selectList: any) {
    console.log(selectList);
    this.tableCheckedList = selectList || []
    // this[action](selectList)
    if (action === 'handleBatchExport') {
      this.openExportDialog('')
    }
    if (action === 'handleBatchContentExport') {
      this.openExportDialog('content')
    }
    // 批量提交质检
    if (action === 'handleBatchSubmitSq') {
      this.handleBatchSubmitSq(selectList);
    }

    // 批量提交质检
    if (action === 'handleBatchCancelSq') {
      this.handleBatchCancelSq(selectList);
    }
  }

  private openExportDialog (flag: string) { // 打开导出的弹窗
    const selectList = this.tableCheckedList || []
    let count = 0
    if (typeof selectList === 'object') { // 单个操作
      count = selectList.length || 0
    } else { // 全选
      count = this.pageData.total
    }
    if (flag === 'content') {
      this.dialogTitle = '批量导出会话内容'
    } else {
      this.dialogTitle = this.activeName === 'session' ? '批量导出会话记录' : '批量导出留言记录'
    }
    this.exportDialogRef.setDialogData({ exportDialog: true, count, dialogTitle: this.dialogTitle })
  }

  private handleDetail (row: any) { // 详情
    this.isShowDrawer = true
    const { visitorId, _id } = row
    let url = '/im-center/action/webchat/queryChatInfoById'
    if (this.activeName === 'leave') {
      url = '/im-center/action/webchat/queryLeaveSessionInfoById'
    }
    const chatInfoActionData = { url, method: 'POST', data: { visitorId, _id } }
    const serveTimeActionData = { url: '/im-center/action/webchat/getServerTimeDiff', method: 'POST', data: { localTimestamp: new Date().getTime() } }
    const queryServeTime = WebchatModule.webchatCommonAction(serveTimeActionData) // 获取服务器时间
    const queryChatInfoById = WebchatModule.queryChatInfoById(chatInfoActionData) // 获取会话详情
    Promise.all([queryChatInfoById, queryServeTime]).then(([chatInfo, serveTime]: any) => {
      if (chatInfo && serveTime && serveTime.serverTime && chatInfo.chatSession) {
        const messageHistoryData = { // 获取消息历史参数
          visitorId,
          dateTime:
            serveTime.serverTime,
          limit: 20,
          _id,
          isNewSession: true,
          webchatType: 'webchatDateCenter',
          sessionId: chatInfo.chatSession._id
        }
        const messageHistoryActionData = { url: '/im-center/action/webchat/queryHistory', method: 'POST', data: messageHistoryData }
        WebchatModule.queryWebchatHistory(messageHistoryActionData).then(res => { // 获取会话历史
          if (res && res.messageList) {
            this.$bus.$emit('initWebchatDataCenter', { chatSession: chatInfo.chatSession, processInfo: chatInfo.scheduleHistory, visitorInfo: chatInfo.visitorInfo || {} })
          }
        })
      }
    })
  }

  private handleSearch (searchForm: any) { // 快捷搜索
    (this.$refs as any).customSearch.hide()
    this.pageData.page = 1
    this.advanceQuery = searchForm
    this.getWebchatList('advanceQuery')
  }

  private getWebchatTabelHeaders () { // 获取会话记录表头
    this.showLoading = true
    this.isShowTabel = false
    const data = { url: '/im-center/action/webchat/header/query', method: 'POST', data: { type: this.activeName } }
    WebchatModule.webchatCommonAction(data).then((res: any) => {
      if (res.success) {
        if (res.data && res.data.config.length > 0) {
          // const customHeaders = this.diffDefaultAndCustomHeaders(this.tableHeaders, res.data.config);
          const headerCloneData: any = deepClone(res.data.config);
          headerCloneData.push({ label: '操作', prop: 'oprate', disenable: true })
          this.$set(this, 'tableHeaders', headerCloneData)
        }
      }
      this.$nextTick(() => {
        this.isShowTabel = true
      })
      this.showLoading = false
    })
  }

  // 兼容新增表头 解决怎加删除表头字段 存储不更新的问题
  private diffDefaultAndCustomHeaders (defaultHeaders, customHeaders) {
    const customReturnArr: any = []; // 返回自定义 为了解决删除表头问题
    const returnArr = defaultHeaders.filter((defaultItem, defaultIndex) => {
      let isProp = false;
      customHeaders.forEach((customItem, customIndex) => {
        if (customItem.prop === defaultItem.prop) {
          const pushItem = deepClone(defaultItem);
          pushItem.show = customItem.show || false;
          customReturnArr.push(pushItem);
          isProp = true;
        }
      });
      return !isProp;
    });
    return deepClone(customReturnArr).concat(returnArr);
  }

  private saveWebchatTabelHeaders (headers: any) { // 自定义表头保存
    if (headers[headers.length - 1].prop === 'oprate') { // 如果表头最后一项是操作需去掉，操作不入库
      headers = headers.slice(0, headers.length - 1)
    }
    const data = { url: '/im-center/action/webchat/header/update', method: 'POST', data: { config: headers, type: this.activeName } }
    WebchatModule.webchatCommonAction(data)
  }

  private closeVideoReplay () {
    this.videoInfo.isShowVideo = false
    this.videoInfo.videoUrl = ''
  }

  private activated () {
    this.$getCache('/im-center/action/config/processConfig/processCache', ['processList'], true).then((res: any) => {
      this.getWebchatList()
    })
  }

  private deactivated () {
    this.isShowDrawer = false
  }

  private closeDraw () {
    this.isShowDrawer = false
  }

  private handleLimit () {
    this.userInfo = this.$store.state.common.session.user
    const limitArr: any[] = []
    const menuArr = ['webchat_session_chat', 'webchat_session_leave'] // 会话记录，留言记录
    const funArr = ['webchat_session_chat_batch_export', 'webchat_content_session_chat_batch_export', 'webchat_session_leave_batch_export', 'webchat_session_chat_batch_commit_cancel_qc'] // 批量导出会话记录， 批量导出留言记录
    menuArr.forEach((item: string) => { // 筛选菜单权限
      if (isHasFuncOrMenus(item, this.userInfo, true)) {
        limitArr.push(item)
      }
    })
    funArr.forEach((item: string) => { // 筛选功能权限
      if (isHasFuncOrMenus(item, this.userInfo, false)) {
        limitArr.push(item)
      }
    })
    console.log(limitArr, 'limitArr')
    this.chatBatchs = this.chatBatchs.filter(item => limitArr.indexOf(item._id) > -1) // 过滤会话记录的批量操作的权限
    this.leaveBatchs = this.leaveBatchs.filter(item => limitArr.indexOf(item._id) > -1) // 过滤留言记录的批量操作的权限
    this.tabPaneList = this.tabPaneList.filter(item => limitArr.indexOf(item._id) > -1) // 过滤菜单权限
    this.activeName = this.tabPaneList[0] ? this.tabPaneList[0].name : 'session'
    this.configBatchs = this.activeName === 'session' ? this.chatBatchs : this.leaveBatchs
  }
  // 质检相关逻辑

  // 提交质检
  private getQualitytestingText (row) {
    const submitStatus: boolean = !!row.applyQualityTime;
    if (submitStatus) {
      return '取消'
    }
  }

  // 获取当前质检记录状态
  private getQtestingStatus (row): string {
    let qtStatus: string;
    if (row.qualityTime) {
      qtStatus = 'scored'
    } else {
      if (row.applyQualityTime) {
        qtStatus = 'submitted'
      } else {
        qtStatus = 'notsubmitted'
      }
    }
    return qtStatus;
  }

  private getQtText (row) {
    const qtStatus = this.getQtestingStatus(row);
    if (qtStatus === 'scored') {
      return '已评分';
    } else if (qtStatus === 'submitted') {
      return '撤销质检'
    } else {
      return '提交质检'
    }
  }

  private getQtIcon (row) {
    const qtStatus = this.getQtestingStatus(row);
    if (qtStatus === 'scored') {
      return 'V7_iconV7tubiao_yitijiaozhijianbingpingfen';
    } else if (qtStatus === 'submitted') {
      return 'V7_iconV7tubiao_yitijiaozhijianweipingfen'
    } else {
      return 'V7_iconV7tubiao_weitijiaozhijian'
    }
  }

  private handleQualitytesting (row: any) {
    const currentId: string = row._id;
    const submitStatus = this.getQtestingStatus(row);
    if (submitStatus === 'submitted') {
      this.cancelQualitytesting([currentId]);
    } else if (submitStatus === 'notsubmitted') {
      if (row.status._id !== 'finish') {
        this.$message.error('当前会话还未结束，无法提交！');
        return false;
      }
      if (row.agentReplyMessageCount === 0) {
        this.$message.error('座席消息数为0，无法提交！')
        return false
      }
      if (row.userId !== (this.userInfo as any)._id) {
        this.$message.error('座席只能处理本人已结束会话');
        return false;
      }
      this.submitQualitytesting([currentId]);
    } else {
      console.log('已评分');
      return false;
    }
  }

  private updateSqStatus (ids, status) {
    ids.forEach((id) => {
      this.webchatList.some((item: any, index) => {
        if (item._id === id) {
          if (status === 'submitted') {
            this.$set(this.webchatList[index], 'applyQualityTime', true);
          } else if (status === 'notsubmitted') {
            this.$set(this.webchatList[index], 'applyQualityTime', false);
          }
          return true;
        }
      });
    })
    this.$message.success('提交成功!');
  }

  private submitQualitytesting (ids) {
    this.$confirm('提交后您的会话将纳入绩效考核，请确认是否提交！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const url = '/im-center/action/quality/applyQuality'
      const sendData = { _ids: ids }
      const actionData = { url, method: 'POST', data: sendData }
      WebchatModule.webchatCommonAction(actionData).then((res: any) => {
        if (res.success) {
          this.$message.success('会话提交成功')
          this.updateSqStatus(ids, 'submitted');
          this.webchatTableRef.cancelSelectFun();
        }
      })
    }).catch(() => {
      this.$message.warning('会话提交已取消')
    })
  }

  private cancelQualitytesting (ids) {
    this.$confirm('撤回后，该会话将不会纳入绩效考核，请确认是否撤回！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const url = '/im-center/action/quality/undoApplyQuality'
      const sendData = { _ids: ids }
      const actionData = { url, method: 'POST', data: sendData }
      WebchatModule.webchatCommonAction(actionData).then((res: any) => {
        if (res.success) {
          this.updateSqStatus(ids, 'notsubmitted');
          this.$message.success('会话撤回成功')
          this.webchatTableRef.cancelSelectFun();
        }
      })
    }).catch(() => {
      this.$message.warning('会话撤回已取消')
    })
  }

  // 批量提交质检
  private handleBatchSubmitSq (ids) {
    if (typeof ids === 'object') {
      this.submitQualitytesting(ids);
    } else {
      this.$message.info('暂不支持全量提交质检');
    }
  }

  // 批量提交质检
  private handleBatchCancelSq (ids) {
    if (typeof ids === 'object') {
      this.cancelQualitytesting(ids);
    } else {
      this.$message.info('暂不支持全量撤销质检');
    }
  }

  private mounted () {
    this.handleLimit() // 权限控制
    this.getWebchatTabelHeaders()
    this.fieldSelectList.toPeer = this.$store.state.common.publicCache.queueList || []
    this.quickSearchForm.advSearchOptions = [ // 快捷检索的数据
      { label: '快捷检索', inputType: 'input', placeholder: '输入会话Id或客户名称', name: 'sessionIdOrVisitorName', clearable: true },
      { label: '接待座席', inputType: 'select', clearable: true, selectData: this.agentList, name: 'userId', multiple: true, defaultProp: { label: 'agentName', value: '_id' } },
      { label: '创建时间', inputType: 'dateTimeRange', clearable: false, name: 'createTime' }
    ]
    const initConfig = this.$store.state.common.initConfig
    const doMain = initConfig && initConfig.qiniuDomainMap ? initConfig.qiniuDomainMap.im : ''
    this.$bus.$on('webchatDataVideoReplay', (res: any) => { // 视频播放信息
      this.videoInfo.chatMsg = res.chatMsg
      this.videoInfo.videoUrl = doMain + '/' + res.chatMsg.content
      this.videoInfo.isShowVideo = true
    })
  }

  private beforeDestroy () {
    this.$bus.$off('webchatDataVideoReplay')
  }

  private beforeMount () {
    const agents = deepClone(this.$store.state.common.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ _id: agents[i]._id, agentName: agents[i].name })
    }
    const webchatType = ['platform', 'finishKey', 'seoSource', 'status', 'sessionType', 'satisfactionName', 'sessionTags'] // 在线缓存
    this.$getCache('/im-center/action/webchat/cache', webchatType, true, true, true, 'POST', true).then((res: any) => {
      if (res && res.success) {
        this.platformObj = this.$store.state.common.publicCache.platformObj || {}
        webchatType.forEach(item => { // 处理在线缓存赋值
          if (item === 'satisfactionName') {
            this.fieldSelectList['satisfactionData.satisfactionName'] = this.$store.state.common.publicCache[item]
          } else if (item === 'sessionTags') {
            this.fieldSelectList[item] = this.$store.state.common.publicCache[item].tree || []
          } else {
            this.fieldSelectList[item] = this.$store.state.common.publicCache[item]
          }
        })
      }
    })
    this.$getCache('/im-center/action/webchat/channelCache', ['cssList', 'channelList'], true).then((res: any) => {
      if (res && res.success) {
        this.fieldSelectList.accessId = this.$store.state.common.publicCache.channelList || []
      }
    })
    this.agentList = agentsArr
    this.fieldSelectList.userId = agentsArr
  }
}
</script>
<style lang="stylus" scoped>
.webchatDataBox
  height 100%
  border-radius 10px
  box-sizing border-box
  padding-top 10px
  .customSearch
    padding 0px
    margin-right 10px
  .V7_iconfont
    color #BEBEC4
    vertical-align middle
  .oprate_span
    margin-right 10px
    cursor pointer
  .oprate_span:hover
    color #008cee
  .oprate-btn
    color $c-main
    margin-right 10px
    cursor pointer
  .tagsItem
    padding 2px 7px
    border-radius 12px
</style>
